﻿using System;
using System.Diagnostics;
using System.Linq;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ebt.Mvvm
{
    public class ListViewWrapper : ControlWrapperBase<ListViewBase>
    {
        public void ScrollIntoView(object item, ScrollIntoViewAlignment alignment = ScrollIntoViewAlignment.Default)
        {
            Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Low, delegate
            {
                foreach (var listView in Elements.ToArray())
                {
                    try
                    {
                        listView.UpdateLayout();
                        if (listView.SemanticZoomOwner == null)
                        {
                            listView.ScrollIntoView(item, alignment);
                        }
                        else
                        {
                            listView.MakeVisible(new SemanticZoomLocation { Item = item });
                        }

                    }
                    catch (Exception e) // Some unexpected exceptions occur.
                    {
                        Debug.WriteLine("ScrollIntoView failed");
                        Debug.WriteLine(e);
                    }
                }
            });
        }
    }
}
